from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.meiduo_admin.serializer.orders import OrderSerializer
from apps.meiduo_admin.utils import PageNum
from apps.order.models import OrderInfo


class OrdersView(ModelViewSet):
    queryset = OrderInfo.objects.all().order_by('order_id')
    permission_classes = [IsAdminUser]
    pagination_class = PageNum
    serializer_class = OrderSerializer

    def get_queryset(self):

        keyword = self.request.query_params.get('keyword')

        if keyword is None or keyword == '':
            return OrderInfo.objects.all().order_by('order_id')
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)

    @action(methods=['put'], detail=True)
    def status(self, request, pk):

        order = self.get_object()
        status = request.data.get('status')

        order.status = status
        order.save()

        ser = self.get_serializer(order)

        return Response({
            'order_id': order.order_id,
            'status': status
        })
